import { getUserList, addNewUser, updateUser, deleteUser } from '@/services/userManage';
import paginationConf from './pagination';
import _ from 'lodash';

const UserManageModel = {
  namespace: 'userManage',
  state: {
    number: 1,
    currentUser: {},
    users: [],
    loading: false,
    selectedRowsKeys: [],
    journal: [],
    journalCharts: [],
    modalVisible: false, //页面是否打开
    userDetail: {},
    versions: [],
    effectPageInfo: {},
    pagination: {
      ...paginationConf,
    },
  },
  effects: {
    *getData({ payload }, { call, put, select }) {
      const pagination = yield select((state) => state.userManage.pagination);
      const response = yield call(getUserList, { ...payload, pagination });
      const userList = _.get(response, 'data.items', []);
      yield put({
        type: 'updateDataSet',
        payload: {
          userList,
          pagination: {
            total: _.get(response, 'data.total', null),
            pageNum: _.get(response, 'data.page', 1),
          },
        },
      });
    },
    changeLoadingStatus(_, { put }) {
      put({
        type: 'changeLoadingStatus',
      });
    },
    *submitUserInfo({ payload, callback }, { call, put }) {
      const { type, formData } = payload;
      // 判断是更新还是新增
      const callFn = type === 'add' ? addNewUser : updateUser;
      const ret = yield call(callFn, formData);
      callback(ret);
    },
    *deleteUserInfo({ payload, callback }, { call }) {
      const ret = yield call(deleteUser, payload)
      callback(ret);
    }
    ,
    changePage({ payload }, { put }) {
      put({
        type: 'changePage',
        payload,
      });
    },
  },
  reducers: {
    updateDataSet(state, { payload }) {
      return {
        ...state,
        users: payload.userList,
        pagination: { ...state.pagination, ...payload.pagination },
        loading: false,
        effectPageInfo: { current: state.pagination.start },
      };
    },
    changeLoadingStatus(state) {
      return { ...state, loading: !state.loading };
    },
    changeModalVisibleAndSetValue(state, { payload }) {
      if (payload.type === 'add') {
        return { ...state, modalVisible: !state.modalVisible, userDetail: {} };
      } else if (payload.type === 'update') {
        return {
          ...state,
          modalVisible: !state.modalVisible,
          userDetail:
            {
              ...payload.data,
            } || {},
        };
      }
      return { ...state, modalVisible: !state.modalVisible };
    },
    clearUserDetail(state) {
      return { ...state, userDetail: {} };
    },
    changePage(state, { payload }) {
      return {
        ...state,
        pagination: { ...state.pagination, start: payload },
      };
    },
  },
};
export default UserManageModel;
